import { Upload, Modal, Icon, Button } from 'antd';
// import { PlusOutlined } from '@ant-design/icons';
import React from 'react';
import { UploadFile, UploadChangeParam, HttpRequestHeader } from 'antd/lib/upload/interface';
import { getUploadImgParam, QiniuUploadParam } from './FileService';

function getBase64(file: Blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export interface ImgVO {
  uid: string;
  size: number;
  name: string;
  fileName?: string;
  url?: string;
  thumbUrl?: string;
  //附件id
  attachmentUrl?: string;
  attachmentId?: number;
  imgUrl?: string;

}
//Array<UploadFile>

export interface UploadProp {
  // getUploadParam: () => void;
  onUploadFinish: (img: Array<ImgVO>) => void;
  // 默认显示图片
  defaultImgUrl?: string;
  imgList: Partial<ImgVO>[];
}

export interface UploadImgState {
  previewVisible: boolean;
  previewImage: string;
  previewTitle: string;
  fileList: Array<Partial<UploadFile>>;
  host: string;
  token: string;
  key: string;
  isShowAllImg: boolean;
}
const baseUrl = process.env.NODE_ENV === 'development' ? '/op' : 'http://47.100.31.123:8080';
export class QiniuUploadImgList extends React.Component<UploadProp, UploadImgState>{
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    host: baseUrl + "/comm/file/uploadFile",
    token: "",
    key: "",
    isShowAllImg: false
  };

  componentDidMount() {
    const { imgList = [] } = this.props;

    // console.log("imgList", imgList);

    // this.setState({
    //   fileList: imgList
    // })
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file: UploadFile) => {
    console.log("file", file);
    if (!file.url) {
      // file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url as string,
      previewVisible: true,
      previewTitle: file.name || (file.url as string).substring((file.url as string).lastIndexOf('/') + 1),
    });
  };

  showAllImg = () => {
    this.setState({ isShowAllImg: true })

  }

  handleChange = ({ fileList }: UploadChangeParam) => {
    this.setState({ fileList });
    console.log("handleChange", fileList);
    const list = fileList.map((file) => {
      if (file.url) {

        const imgVO: ImgVO = {
          ...file,
          attachmentUrl: file.url,
          attachmentId: parseInt(file.uid)
        }
        return imgVO;

      } else {
        const imgVO: ImgVO = {
          ...file,
          attachmentUrl: file.response ? file.response.result.url : undefined,
          attachmentId: file.response ? file.response.result.id : undefined,
        }
        return imgVO;
      }

    });
    this.props.onUploadFinish(list);
  }

  render() {
    const { previewVisible, token, key, isShowAllImg, previewImage, fileList, previewTitle, host } = this.state;
    const { imgList } = this.props;
    const data = { token, key };
    const header: HttpRequestHeader = { "X-EI-AppCode": " 101" };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    console.log("imgList", imgList);
    let defaultFiles: UploadFile[] = [];
    if (imgList && imgList.length > 0) {
      defaultFiles = imgList.map((img: Partial<ImgVO>, index: number) => {
        //TODO 优化 解决循环出现  "-list_big" 的原因
        let url = img.url;
        const file: UploadFile = {
          uid: img.uid || img.attachmentId!.toString(),
          size: 100,
          name: (index + ".png"),
          url,
          type: "image/jpeg",
        }
        return file;
      })
    }
    /**
     * 如果state的数据，有值，展示出啦，没值，展示默认值
     * 如果先展示了默认值，在选择，则新的onChange的参数，必然包含了原有的数据
     */
    // const list = (fileList && fileList.length > 0) ? fileList : defaultFiles;
    // console.log(fileList, defaultFiles);
    // console.log("fileList", fileList);
    return (
      <div className="clearfix" >
        <Upload
          name="file"
          action={host}
          data={data}
          listType="picture-card"
          fileList={defaultFiles}
          // defaultFileList={defaultFiles}
          onPreview={this.handlePreview}
          onChange={this.handleChange}

          headers={header}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <div>
          <Button onClick={this.showAllImg}>预览商品详情</Button>
        </div>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>

        <Modal
          visible={isShowAllImg}
          title="预览"
          footer={null}
          onCancel={() => { this.setState({ isShowAllImg: false }) }}
        >
          {
            (defaultFiles && defaultFiles.length > 0) ? defaultFiles.map((file: UploadFile) => {
              //TODO 优化图片显示，这里加上了 -list_big,不然无法显示
              return <img key={file.name} alt="all" style={{ width: '100%' }} src={file.url} />
            }) : null
          }
        </Modal>
      </div>
    );
  }
}

export default QiniuUploadImgList;